#include <string>
#include <iostream>
#include <locale>
#include <gtk/gtk.h>
#include "Ui.h"
#include "utils.h"
#include "LyricUi.h"
#include "LyricTool.h"
#include "kugou.h"
#include "lyric_log.h"

//typedef struct {
//    GtkWidget *title_label;
//    GtkWidget *lyric_view;
//    GtkTextBuffer *lyric_buffer;
//    GList *lyrics; // 每行歌词结构体
//    int current_line;
//    int scroll_line;
//	int scroll_offset;
//} LyricWidget;
//
//typedef struct {
//    gchar *text;
//    gint timestamp; // 毫秒
//    int start_offset;
//    int end_offset;
//} LyricLine;

typedef struct {
    GList* music_list;
    GList* cursor;
    LyricWidget* widget;
}MusicPlay;


//#ifdef __cplusplus
//extern "C" {
//#endif
// 导入外部函数
gboolean is_playing(gpointer track) {
    return true;
}
gchar* get_artist(gpointer track) {
    return g_strdup("未知歌手");
}
gchar* get_title(gpointer track) {
    return g_strdup("未知标题");
}

static LyricLine* past_line = NULL;
LyricWidget* g_lyric_widget = NULL;
// 你需要定时调用 update_lyrics(widget, current_time_ms) 来动态高亮歌词

typedef struct {
    LyricWidget *lyric_widget;
    gdouble current_time_ms;
    guint timer_id;
} TimerData;

gboolean timer_callback(gpointer user_data) {
    TimerData *data = (TimerData*)user_data;
    //update_lyricsX(data->lyric_widget, data->current_time_ms);
    update_lyrics(data->lyric_widget, data->current_time_ms);
    data->current_time_ms += 0.5f;
    return TRUE;
}

static MusicPlay* music_play;

float current_time_ms = 0.0f;
float get_position(gpointer user_data) {
    LyricWidget* lyric_widget = (LyricWidget*)user_data;
    if (lyric_widget->timer_id != 0) {
        current_time_ms += 0.3f;
    }
    else {
        current_time_ms = 0.0f;
    }
    return current_time_ms;
}

void on_window_destroy(GtkWidget *widget, gpointer user_data) {
    LyricWidget* lyric_widget = (LyricWidget*)user_data;

    clear_widget(lyric_widget);
    g_free(lyric_widget);
}


void set_new_lyrics(MusicPlay* musicPlay, gchar* location) {
    gchar* basename = g_path_get_basename(location);
    gchar* dot = strrchr(basename, '.');
    if (dot) *dot = '\0';
    gchar* split = strrchr(basename, '-');
    if (split) *split = '\0';
    gchar* title = split + 1;
    gchar* artist = basename;

    current_time_ms = 0;
    lyric_log_info("切换歌曲--------------");
    lyric_log_info("歌名: %s", title);
    lyric_log_info("歌手: %s", artist);

    // 使用SetLyricsUIData结构体调用set_lyrics
    SetLyricsUIData* ui_data = g_new0(SetLyricsUIData, 1);
    ui_data->widget = musicPlay->widget;
    g_strlcpy(ui_data->title, title, sizeof(ui_data->title));
    g_strlcpy(ui_data->artist, artist, sizeof(ui_data->artist));
    g_strlcpy(ui_data->location, location, sizeof(ui_data->location));
    ui_data->song_seq = get_next_sequence();
    ui_data->lyrics_temp = NULL;
    set_lyrics(ui_data);
    g_free(basename);
}


// 确定按钮点击回调函数
static void on_pre10_clicked(GtkWidget* widget, gpointer data) {
    MusicPlay* musicPlay = (MusicPlay*)data;
    int i = 10;
    while (musicPlay->cursor && musicPlay->cursor->prev && i>0) {
        musicPlay->cursor = musicPlay->cursor->prev;
        i--;
    }

    if (!musicPlay->cursor) {
        musicPlay->cursor = musicPlay->music_list;
    }

    if (musicPlay->cursor) {
        gchar* location = (gchar*)musicPlay->cursor->data;
        if (!location)
            return;
        set_new_lyrics(musicPlay, location);
    }
}

// 确定按钮点击回调函数
static void on_pre_clicked(GtkWidget* widget, gpointer data) {
    MusicPlay* musicPlay = (MusicPlay*)data;
    if (musicPlay->cursor) {
        musicPlay->cursor = musicPlay->cursor->prev;
    }
    else {
        musicPlay->cursor = musicPlay->music_list;
    }
    if (musicPlay->cursor) {
        gchar* location = (gchar*)musicPlay->cursor->data;
        if (!location)
            return;
        set_new_lyrics(musicPlay, location);
    }
}

// 取消按钮点击回调函数
static void on_next_clicked(GtkWidget* widget, gpointer data) {
    MusicPlay* musicPlay = (MusicPlay*)data;
    if (musicPlay->cursor) {
        musicPlay->cursor = musicPlay->cursor->next;
    }
    else {
        musicPlay->cursor = musicPlay->music_list;
    }
    if (musicPlay->cursor) {
        gchar* location = (gchar*)musicPlay->cursor->data;
        if (!location)
            return;
        set_new_lyrics(musicPlay, location);

    }
}

static void on_next10_clicked(GtkWidget* widget, gpointer data) {
    MusicPlay* musicPlay = (MusicPlay*)data;
    int i = 10;
    while (musicPlay->cursor && musicPlay->cursor->next && i > 0) {
        musicPlay->cursor = musicPlay->cursor->next;
        i--;
    }

    if (!musicPlay->cursor) {
        musicPlay->cursor = musicPlay->music_list;
    }

    if (musicPlay->cursor) {
        gchar* location = (gchar*)musicPlay->cursor->data;
        if (!location)
            return;
        set_new_lyrics(musicPlay, location);
    }
}

static void
activate(GtkApplication *app,
         gpointer user_data) {
    // 构造测试歌词
    //GList *lyrics = NULL;
    //for (int i=0;i<30;i++) {
    //    LyricLine *line1 = g_slice_new0(LyricLine);
    //    char linestr[100] = {};
    //    sprintf(linestr, "第%i行歌词",i+1);
    //    line1->text = g_strdup(linestr);
    //    line1->timestamp = i*1000;
    //    lyrics = g_list_append(lyrics, line1);
    //}
    music_play = g_new0(MusicPlay, 1);

    const gchar* root_dir = read_from_file("musicpath.txt");  // 替换为目标目录
    if (!root_dir) {
        lyric_log_error("musicpath.txt not found or failed to read, using default path");
        root_dir = "~/music";
    }
    GList* file_list = NULL;
    // 定义要筛选的后缀列表（不区分大小写）
    const gchar* extensions[] = { "mp3", "flac", "wav", "mp4" };
    gsize ext_count = G_N_ELEMENTS(extensions);

    // 遍历目录（带后缀筛选）
    traverse_directory_ext(root_dir, &file_list, extensions, ext_count);
    // 打印所有文件路径
    GList* iter;
    for (iter = file_list; iter != NULL; iter = iter->next) {
        g_print("%s\n", (gchar*)iter->data);
    }
    // 释放资源
    //g_list_free_full(file_list, g_free);

    //GList* lyrics = load_lyrics("H:\\music\\kwvip\\刘珂矣-半壶纱.lrc");
    //int len = g_list_length(lyrics);

    // 创建窗口
    GtkWidget *window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "歌词组件Demo");
    gtk_window_set_default_size(GTK_WINDOW(window), 400, 500);

    // 创建主垂直布局容器
    GtkWidget* vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
    gtk_container_add(GTK_CONTAINER(window), vbox);

    // 创建歌词组件
    //GtkWidget *lyric_box = lyric_widget_new_x("测试歌曲", "测试歌手", lyrics);
    //LyricWidget *lyric_widget = (LyricWidget *)g_object_get_data(G_OBJECT(lyric_box), "lyric-widget");
    LyricWidget* lyric_widget = lyric_widget_new();
    music_play->music_list = file_list;
    music_play->widget = lyric_widget;
    lyric_widget->get_position = get_position;
    
    // 使用SetLyricsUIData结构体调用set_lyrics
    SetLyricsUIData* ui_data = g_new0(SetLyricsUIData, 1);
    ui_data->widget = lyric_widget;
    g_strlcpy(ui_data->title, "当年的我们", sizeof(ui_data->title));
    g_strlcpy(ui_data->artist, "程响", sizeof(ui_data->artist));
    g_strlcpy(ui_data->location, "~/music/当年的我们-程响.flac", sizeof(ui_data->location));
    ui_data->song_seq = get_next_sequence();
    ui_data->lyrics_temp = NULL;
    set_lyrics(ui_data);
    
    g_signal_connect(lyric_widget->lyric_view, "populate-popup", G_CALLBACK(on_populate_popup), lyric_widget);
    g_signal_connect(lyric_widget->lyric_view, "button-press-event", G_CALLBACK(on_button_press_event), lyric_widget);
    //init_lyric(lyric_widget, "半壶纱", "刘珂矣", lyrics);

    //gtk_container_add(GTK_CONTAINER(window), lyric_widget->lyric_container);
    gtk_box_pack_start(GTK_BOX(vbox), lyric_widget->lyric_container, TRUE, TRUE, 0);
    // 创建底部水平按钮容器
    GtkWidget* hbutton_box = gtk_button_box_new(GTK_ORIENTATION_HORIZONTAL);
    gtk_button_box_set_layout(GTK_BUTTON_BOX(hbutton_box), GTK_BUTTONBOX_END);
    gtk_box_pack_end(GTK_BOX(vbox), hbutton_box, FALSE, TRUE, 5);
    // 创建两个按钮
    GtkWidget* button_pre10 = gtk_button_new_with_label("上十首");
    GtkWidget* button_pre = gtk_button_new_with_label("上一首");
    GtkWidget* button_next = gtk_button_new_with_label("下一首");
    GtkWidget* button_next10 = gtk_button_new_with_label("下十首");
    gtk_container_add(GTK_CONTAINER(hbutton_box), button_pre10);
    gtk_container_add(GTK_CONTAINER(hbutton_box), button_pre);
    gtk_container_add(GTK_CONTAINER(hbutton_box), button_next);
    gtk_container_add(GTK_CONTAINER(hbutton_box), button_next10);
    // 连接按钮信号
    g_signal_connect(button_pre10, "clicked", G_CALLBACK(on_pre10_clicked), music_play);
    g_signal_connect(button_pre, "clicked", G_CALLBACK(on_pre_clicked), music_play);
    g_signal_connect(button_next, "clicked", G_CALLBACK(on_next_clicked), music_play);
    g_signal_connect(button_next10, "clicked", G_CALLBACK(on_next10_clicked), music_play);

    gtk_widget_show_all(window);

    // 启动定时器模拟歌词滚动
    //TimerData *timer_data = g_new0(TimerData, 1);
    //timer_data->lyric_widget = lyric_widget;
    //timer_data->current_time_ms = 0;
    //timer_data->timer_id = g_timeout_add(500, timer_callback, timer_data);

    g_signal_connect(window, "destroy", G_CALLBACK(on_window_destroy), lyric_widget);
}



int main(int argc, char **argv) {
    GtkApplication *app;
    int status;
    
    std::locale::global(std::locale("zh_CN.UTF-8"));
    gtk_init(&argc, &argv);
    
    // 初始化日志系统（独立运行模式）
    lyric_log_init(default_log_output, 1, LYRIC_LOG_LEVEL_DEBUG);

    app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect(app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);
    
    // 清理日志系统
    lyric_log_cleanup();

    return status;
}

int mainx(int argc, char** argv) {
    gtk_init (&argc, &argv);
    // 设置全局locale为UTF-8 
    std::locale::global(std::locale("zh_CN.UTF-8"));
    lyric_log_info("Hello World!");

    LyricConfig* lrc_config = g_new0(LyricConfig, 1);
    lrc_config->text = "~/music/刘珂矣-半壶纱.lrc";
    //load_lyrics(lrc_config);

    return 0;
}
